<template>
  <div class="app-container">
    <el-row :gutter="20">

      <!--用户数据-->
      <el-col :span="24" :xs="24">

        <!-- 查询区域 开始 -->
       <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">

        <el-form-item label="归属部门" prop="deptId">
          <treeselect style="width: 200px"
                      :disabled="isHiddenOrReadOnly"
                      v-model="queryParams.deptId"
                      :options="deptOptions"
                      placeholder="请选择归属部门" />
        </el-form-item>

         <!--根据月份自动生成默认社保账单-->
         <el-form-item label="社保账单月份" prop="billDate" label-width="98px">
           <el-date-picker clearable size="small" style="width: 200px;"
                           :disabled="isHiddenOrReadOnly"
                           v-model="queryParams.billDate"
                           type="month"
                           value-format="yyyy-MM"
                           placeholder="选择社保账单月份">
           </el-date-picker>
         </el-form-item>

         <!--根据月份自动生成默认社保账单-->
         <el-form-item label="社保费用月份" prop="costDate" label-width="98px">
           <el-date-picker clearable size="small" style="width: 200px;"
                           :disabled="isHiddenOrReadOnly"
                           v-model="queryParams.costDate"
                           type="month"
                           value-format="yyyy-MM"
                           placeholder="选择社保费用月份">
           </el-date-picker>
         </el-form-item>


          <el-form-item>
            <el-button v-if="!isHiddenOrReadOnly" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <!--<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
            <el-button
              type="success"
              v-if="!isHiddenOrReadOnly"
              icon="el-icon-refresh"
              size="mini"
              @click="handleCreateDefault"
              v-hasPermi="['hr:attendance:export']"
            >生成默认社保账单
            </el-button>


            <el-button
              type="danger"
              v-if="!isHiddenOrReadOnly"
              icon="el-icon-upload2"
              size="mini"
              @click="handleSubmitNext"
              v-hasPermi="['hr:attendance:export']"
            >提交
            </el-button>

          </el-form-item>
        </el-form>

        <!-- 查询区域 结束 -->


        <el-table
          class="list-table"
          v-loading="loading"
          :data="dataList"
          stripe
          size="small"
          fit
          highlight-current-row
          @selection-change="handleSelectionChange"
          style="width: 100%;">
          <el-table-column type="selection" width="55" align="center"/>
          <!--<el-table-column label="ID" align="center" prop="id"/>-->
          <el-table-column label="员工" align="center" prop="employeeName"/>
          <el-table-column label="账单年月（缴费年月）" align="center" prop="billDate"/>
          <el-table-column label="费用年月" align="center" prop="costDate"/>
          <el-table-column label="社保基数" align="center" prop="baseSocialSecurity"/>
          <el-table-column label="公积金基数" align="center" prop="baseProvidentFund"/>
          <el-table-column label="个人社保扣除" align="center" prop="personalSocialSecurityCost"/>
          <el-table-column label="个人公积金扣除" align="center" prop="personalProvidentFundCost"/>
          <el-table-column label="公司社保扣除" align="center" prop="companySocialSecurityCost"/>
          <el-table-column label="公司公积金扣除" align="center" prop="companyProvidentFundCost"/>
          <el-table-column label="最后更新日期" align="center" prop="updateTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime,'{y}年{m}月{d}日') }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['hr:attendance:edit']"
              >修改
              </el-button>

            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>


    <!-- 添加或修改社保对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px">
      <el-form class="editInfo" ref="form" :inline="true" :model="form" :rules="rules" size="small"
               label-width="120px">
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input style="color: #000;" disabled="true" v-model="form.employeeName"/>
        </el-form-item>
        <el-form-item label="账单年月（缴费年月）" prop="billDate">
          <el-input v-model.number="form.billDate"/>
        </el-form-item>
        <el-form-item label="费用年月" prop="costDate">
          <el-input v-model.number="form.costDate"/>
        </el-form-item>
        <el-form-item label="社保基数" prop="baseSocialSecurity">
          <el-input v-model.number="form.baseSocialSecurity"/>
        </el-form-item>
        <el-form-item label="公积金基数" prop="baseProvidentFund">
          <el-input v-model.number="form.baseProvidentFund" />
        </el-form-item>
        <el-form-item label="个人社保扣除" prop="personalSocialSecurityCost">
          <el-input v-model.number="form.personalSocialSecurityCost"/>
        </el-form-item>
        <el-form-item label="个人公积金扣除" prop="personalProvidentFundCost">
          <el-input v-model.number="form.personalProvidentFundCost"/>
        </el-form-item>
        <el-form-item label="公司社保扣除" prop="companySocialSecurityCost">
          <el-input v-model.number="form.companySocialSecurityCost" />
        </el-form-item>
        <el-form-item label="公司公积金扣除" prop="companyProvidentFundCost">
          <el-input v-model.number="form.companyProvidentFundCost"/>
        </el-form-item>
        <el-form-item label="最后更新日期" prop="updateTime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.updateTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择社保账单日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  //待修改，需要改成社保的
  import {
    listAttendance,
    getAttendance,
    delAttendance,
    addAttendance,
    updateAttendance,
    exportAttendance,
    addCreateDefault,
    addAttendanceConfirm
  } from '@/api/hr/attendance'

  import { treeselect } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    components: { Treeselect },
    data() {
      return {
        chooseMonth : undefined,
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 社保表格数据
        dataList: [{
          id: undefined,
          employeeName: '亚瑟',
          billDate: '2019-02',
          costDate: '2019-01',
          baseSocialSecurity: 6,
          baseProvidentFund: 6,
          personalSocialSecurityCost: 6,
          personalProvidentFundCost: 6,
          companySocialSecurityCost: 6,
          companyProvidentFundCost: 6,

        },{
          id: undefined,
          employeeName: '亚瑟',
          billDate: '2019-02',
          costDate: '2019-01',
          baseSocialSecurity: 6,
          baseProvidentFund: 6,
          personalSocialSecurityCost: 6,
          personalProvidentFundCost: 6,
          companySocialSecurityCost: 6,
          companyProvidentFundCost: 6,

        },{
          id: undefined,
          employeeName: '亚瑟',
          billDate: '2019-02',
          costDate: '2019-01',
          baseSocialSecurity: 6,
          baseProvidentFund: 6,
          personalSocialSecurityCost: 6,
          personalProvidentFundCost: 6,
          companySocialSecurityCost: 6,
          companyProvidentFundCost: 6,

        },{
          id: undefined,
          employeeName: '亚瑟',
          billDate: '2019-02',
          costDate: '2019-01',
          baseSocialSecurity: 6,
          baseProvidentFund: 6,
          personalSocialSecurityCost: 6,
          personalProvidentFundCost: 6,
          companySocialSecurityCost: 6,
          companyProvidentFundCost: 6,

        }],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 部门树选项
        deptOptions: undefined,
        // 部门名称
        deptName: undefined,
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          employeeName: undefined,
          dueDays: undefined,
          attendanceMonth: undefined,
          overtimeDays: undefined,
          leaveDays: undefined,
          diseaseDays: undefined,
          weddingDays: undefined,
          funeralDays: undefined,
          absenteeismDays: undefined,

          //add

          billDate: undefined , //账单年月
          costDate: undefined , //费用年月

        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          billDate: [
            { required: true, message: '账单年月（缴费年月）不能为空！', trigger: 'blur' }
          ], costDate: [
            { required: true, message: '费用年月不能为空！', trigger: 'blur' }
          ], baseSocialSecurity: [
            { required: true, message: '社保基数不能为空！', trigger: 'blur' }
          ], baseProvidentFund: [
            { required: true, message: '公积金基数不能为空！', trigger: 'blur' }
          ], personalSocialSecurityCost: [
            { required: true, message: '个人社保扣除不能为空！', trigger: 'blur' }
          ], personalProvidentFundCost: [
            { required: true, message: '个人公积金扣除不能为空！', trigger: 'blur' }
          ], companySocialSecurityCost: [
            { required: true, message: '公司社保扣除不能为空！', trigger: 'blur' }
          ], companyProvidentFundCost: [
            { required: true, message: '公司公积金扣除不能为空！', trigger: 'blur' }
          ]
        },
        //add by yyf on 2020-1-20
        isHiddenOrReadOnly : false
      }
    },
    watch: {
      // 根据名称筛选部门树
     /* deptName(val) {
        this.$refs.tree.filter(val)
      }*/
    },


    created() {

      //this.getList()

      this.getTreeselect()

      //如果是社保账单页面点编辑进来的，就默认设置部门和社保账单月份，并且查询具体社保账单人员的数据
      if(this.$router.query){
        this.isHiddenOrReadOnly = true;
        this.queryParams.deptId = this.$router.query.deptId;
        this.queryParams.billDate = this.$router.query.billDate; //接收上一个页面的账单年月
        this.getList();
      }else{
        //如果是社保账单页面点填报按钮进来的，允许修改部门和社保账单月份，显示生成按钮

      }

    },
    methods: {
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data
        })
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptId = data.id
        this.getList()
      },
      /** 查询社保列表 */
      getList() {

        return ; // 因为接口不存在，暂时屏蔽掉吧

        this.loading = false; //方便测试，取消遮罩层
        listAttendance(this.queryParams).then(response => {
          this.dataList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          employeeId: undefined,
            billDate: undefined,
            costDate: undefined,
            baseSocialSecurity: undefined,
            baseProvidentFund: undefined,
            personalSocialSecurityCost: undefined,
            personalProvidentFundCost: undefined,
            companySocialSecurityCost: undefined,
            companyProvidentFundCost: undefined,

        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加社保'
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id || this.ids
        this.open = true
        this.title = '修改社保'
        getAttendance(id).then(response => {
          this.form = response.data
          this.open = true
          this.title = '修改社保'
        })


      },

      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateAttendance(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            } else {
              addAttendance(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$confirm('是否确认删除社保编号为"' + ids + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delAttendance(ids)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(function() {
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有社保数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return exportAttendance(queryParams)
        }).then(response => {
          this.download(response.msg)
        }).catch(function() {
        })
      },

      //add by yyf
      //提交本月社保账单数据
      handleSubmitNext(){
        if(!this.chooseMonth){
          this.msgError('请选择月份！')
          return;
        }

        if(!this.queryParams.deptId){
          this.msgError('请选择部门！')
          return;
        }

        var that = this;


        this.$confirm('是否确认提交所有数据，注意，提交后将不能修改！！', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return addAttendanceConfirm({
            attendanceMonth : this.chooseMonth,
            deptId : this.queryParams.deptId
          })
        }).then(response => {
          if (response.code === 200) {
            that.msgSuccess('创建成功')

            //提交确认后，状态是已确认的将不可编辑
            //这边就重新加载列表，后台应该给我返回空（关联社保账单主表，不能只能查询编辑中的详细数据给我）

            this.getList();

          } else {
            this.msgError(response.msg)
          }


        }).catch(function() {

        });




      },


      //add by yyf
      //根据月份和部门编号，生成默认社保账单
      handleCreateDefault() {
        if(!this.chooseMonth){
          this.msgError('请选择月份！')
          return;
        }

        if(!this.queryParams.deptId){
          this.msgError('请选择部门！')
          return;
        }

        var that = this;

          // 后台生成逻辑 还需要 插入一条记录到社保账单确认表，状态是编辑中
          addCreateDefault({
            attendanceMonth : this.chooseMonth,
            deptId : this.queryParams.deptId
          }).then(response => {
            if (response.code === 200) {
              that.msgSuccess('创建成功')
              this.getList(); // 创建成功以后，查询刚刚生成的社保账单默认数据，然后再一条一条编辑吧
            } else {
              this.msgError(response.msg)
            }
          })



      }
    }
  }
</script>
